<?php
$acctpath = "data/accounts.xml";
$indexpath = "index.php";
$prodpath = "data/products.xml";
require_once "data/SessionControl.php";

function sanitize($data){
    foreach($data as $key=>$val){
        $data[$key] = sanitizeString ($val);
    }
    return $data;
}

function sanitizeString($var){
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    $var = str_ireplace("/^[\s]+|[\s]+$/", "", $var);
    return $var;
}

function accountExists($data){
    $error = "";
    $accts = simplexml_load_file($GLOBALS['acctpath']);
    for ($i = 0; $i < count($accts->children()); $i++){
        if($data["emailreg"] == $accts->account[$i]->email){
            $error = "Account already exists.";
            break;
        }
    }
    return $error;
}

function allowLogin($data){
    $data = sanitize($data);
    $accts = simplexml_load_file($GLOBALS['acctpath']);
    $error = "Account does not exist or entered password is wrong.";
    for ($i = 0; $i < count($accts->children()); $i++){
        if($data["emaillog"] == $accts->account[$i]->email && md5($data["password"]) == $accts->account[$i]->password){
            $error = "";
            break;
        }
    }
    return $error;
}

function saveAccount($data){
    $accts = new DOMDocument();
    $accts->load($GLOBALS['acctpath']);

    $fields = array("firstname","lastname","address","email","password");

    $newAcct = $accts->createElement("account");

    $i = 0;
    foreach($data as $key=>$val){
        if($key != "submitreg" && $key != "password2"){
            $newCRLF = $accts->createTextNode("\n        ");
            $newAcct->appendChild($newCRLF);
            if($key == "password1")
                $newField = $accts->createElement($fields[$i++],md5($val));
            else
                $newField = $accts->createElement($fields[$i++],$val);
            $newAcct->appendChild($newField);
        }
    }
    $newCRLF = $accts->createTextNode("\n    ");
    $newAcct->appendChild($newCRLF);

    $acct = $accts->getElementsByTagName("accounts")->item(0);

    $newCRLF = $accts->createTextNode("    ");
    $acct->appendChild($newCRLF);

    $acct->appendChild($newAcct);

    $newCRLF = $accts->createTextNode("\n");
    $acct->appendChild($newCRLF);

    $accts->save($GLOBALS['acctpath']);
    
    header('location: '.$GLOBALS['indexpath']);
}

function getInfo($email){
    $accts = simplexml_load_file($GLOBALS['acctpath']);
    $found = false;
    for ($i = 0; $i < count($accts->children()); $i++){
        if($email == $accts->account[$i]->email){
            $found = true;
            break;
        }
    }
    if($found){
        $fields = array("firstname","lastname","address","email","password");
        $data["firstname"] = $accts->account[$i]->firstname;
        $data["lastname"] = $accts->account[$i]->lastname;
        $data["address"] = $accts->account[$i]->address;
        $data["email"] = $accts->account[$i]->email;
        $data["password"] = $accts->account[$i]->password;
        return $data;
    }
    else{
        return array('error'=>'The system met an unexpected error and cannot find your account info');
    }
}
function getAlbum($id){
    $prods = simplexml_load_file($GLOBALS['prodpath']);
    $found = false;
    for ($i = 0; $i < count($prods->children()); $i++){
        if($id == $prods->album[$i]->id){
            $found = true;
            $a_Id = $i;
            break;
        }
    }
    if($found){
        $i = 0;
        foreach($prods->album[$a_Id]->songs->children() as $song){
            foreach($song as $key=>$attr)
                $s[$key] = $attr;
            $songs[$i++] = $s;
        }
        return $songs;
    }
    else{
        return array('error'=>'The system met an unexpected error and cannot find the album info');
    }
}

function isAdmin($email){
    /*$xml = simplexml_load_file($GLOBALS['acctpath']);
    $node = $xml->xpath("/accounts/account[@type='admin']/email='.$email.'");
    if (!empty($node)) {
        return true;
    } else {
        return false;
    }*/
    $doc = new DOMDocument;
    $doc->load($GLOBALS['acctpath']);
    $xpath = new DOMXPath($doc);
    $query = "/accounts/account[@type='admin']/email";
    $entries = $xpath->query($query);
    foreach($entries as $entry)
       if($entry->nodeValue == $email) return true;
    return false;
}

function addAlbum($album,$songs){
    $doc = new DOMDocument;
    $doc->load($GLOBALS['prodpath']);
    $xpath = new DOMXPath($doc);
    $fields = array("albumtitle","artist","albumart","genre","desc","year");
    $fields2 = array("trackno","title","duration","fileloc","price");
   
    $newAlbum = $doc->createElement("album");
    
    $newAlbum->appendChild($doc->createTextNode("\n        "));
    $count = $xpath->query("/albums/album[last()]/id")->item(0)->nodeValue+1;
    $newAlbum->appendChild($doc->createElement("id",$count));

    $i = 0;
    foreach($album as $key=>$val){
        $newCRLF = $doc->createTextNode("\n        ");
        $newAlbum->appendChild($newCRLF);
        $newField = $doc->createElement($fields[$i++],$val);
        $newAlbum->appendChild($newField);
    }
    
    $newSongs = $doc->createElement("songs");
    foreach($songs as $song){
        $newSong = $doc->createElement("song");
        $newSong->setAttribute('hits', 0);
        $i = 0;
        foreach ($song as $key=>$val){
            $newCRLF = $doc->createTextNode("\n                ");
            $newSong->appendChild($newCRLF);
            $newField = $doc->createElement($fields2[$i++],$val);
            $newSong->appendChild($newField);
        }
        $newSong->appendChild($doc->createTextNode("\n            "));
        $newSongs->appendChild($doc->createTextNode("\n            "));
        $newSongs->appendchild($newSong);
    }
    $newSongs->appendChild($doc->createTextNode("\n        "));
    $newAlbum->appendChild($doc->createTextNode("\n        "));
    $newAlbum->appendChild($newSongs);
    
    $newCRLF = $doc->createTextNode("\n    ");
    $newAlbum->appendChild($newCRLF);

    $album = $doc->getElementsByTagName("albums")->item(0);

    $newCRLF = $doc->createTextNode("    ");
    $album->appendChild($newCRLF);

    $album->appendChild($newAlbum);

    $newCRLF = $doc->createTextNode("\n");
    $album->appendChild($newCRLF);

    $doc->save($GLOBALS['prodpath']);
}

function searchAlbum($album){
    $doc = new DOMDocument;
    $doc->load($GLOBALS['prodpath']);
    $xpath = new DOMXPath($doc);
    $query = "/albums/album[albumtitle=]";
    $entries = $xpath->query($query);
    foreach($entries as $entry)
       if($entry->nodeValue == $email) return true;
    return false;
}

function editAlbum($album){
    $doc = new DOMDocument;
    $doc->load($GLOBALS['prodpath']);
    $xpath = new DOMXPath($doc);
    $fields = array("albumtitle","artist","albumart","genre","desc","year");
    $query = '/albums/album[id='.$album['editalbumid'].']';
    //echo $album['editalbumid'];
    if(!strcasecmp($xpath->query($query.'/'.$fields[0])->item(0)->nodeValue,$album['editalbumnm']) || ($album['editalbumnm'] != ''))
        $xpath->query($query.'/'.$fields[0])->item(0)->nodeValue = $album['editalbumnm'];
    
    if(!strcasecmp($xpath->query($query.'/'.$fields[1])->item(0)->nodeValue,$album['editalbumartist']) || ($album['editalbumartist'] != ''))
        $xpath->query($query.'/'.$fields[1])->item(0)->nodeValue = $album['editalbumartist'];
    /*
    if(!strcasecmp($xpath->query($query.'/'.$fields[2])->item(0)->nodeValue,$album['editalbumart']) || ($album['editalbumart'] != ''))
        $xpath->query($query.'/'.$fields[2])->item(0)->nodeValue = $album['editalbumart'];
    */
    if(!strcasecmp($xpath->query($query.'/'.$fields[3])->item(0)->nodeValue,$album['editalbumgenre']) || ($album['editalbumgenre'] != ''))
        $xpath->query($query.'/'.$fields[3])->item(0)->nodeValue = $album['editalbumgenre'];
    
    if(!strcasecmp($xpath->query($query.'/'.$fields[4])->item(0)->nodeValue,$album['editalbumdesc']) || ($album['editalbumdesc'] != ''))
        $xpath->query($query.'/'.$fields[4])->item(0)->nodeValue = $album['editalbumdesc'];
    
    if(!strcasecmp($xpath->query($query.'/'.$fields[5])->item(0)->nodeValue,$album['editalbumyr']) || ($album['editalbumyr'] != ''))
        $xpath->query($query.'/'.$fields[5])->item(0)->nodeValue = $album['editalbumyr'];
    //echo $album['editalbumartist'];
    //for($i = 0; $i < 6; $i++) echo $xpath->query($query.'/'.$fields[$i])->item(0)->nodeValue;
    //echo ('hahaha');
    $doc->save($GLOBALS['prodpath']);
}

function delAlbum($album){
    $doc = new DOMDocument;
    $doc->load($GLOBALS['prodpath']);
    $xpath = new DOMXPath($doc);
    foreach($xpath->query('/albums/album[id='.$album['delalbumid'].']') as $entry)
        $entry->parentNode->removeChild($entry);
    $doc->save($GLOBALS['prodpath']);
}

function delAccount($account){
    $doc = new DOMDocument;
    $doc->load($GLOBALS['acctpath']);
    $xpath = new DOMXPath($doc);
    $query = '/accounts/account[email="'.$account['hiddenemail2'].'"]';
    foreach($xpath->query($query) as $entry)
        $entry->parentNode->removeChild($entry);
    $doc->save($GLOBALS['acctpath']);
}

function editAccount($account){
    $doc = new DOMDocument;
    $doc->load($GLOBALS['acctpath']);
    $xpath = new DOMXPath($doc);
    $query = '/accounts/account[email="'.$account['hiddenemail'].'"]';
    //echo $account['hiddenemail'];
    //foreach($xpath->query($query.'/password') as $entry) echo $xpath->query($query.'/password')->item(0)->nodeValue;
    //echo $xpath->query($query.'/password')->item(0)->nodeValue.'<br>';
    if($xpath->query($query)->length > 0){
        if(isset($account['password1'])){
            if(md5($account['password1']) == $xpath->query($query.'/password')->item(0)->nodeValue)
                    $xpath->query($query.'/password')->item(0)->nodeValue = md5($account['password2']);
            else return false;
        }
        $xpath->query($query.'/firstname')->item(0)->nodeValue = $account['fname'];
        $xpath->query($query.'/lastname')->item(0)->nodeValue = $account['lname'];
        $xpath->query($query.'/address')->item(0)->nodeValue = $account['address'];

        $doc->save($GLOBALS['acctpath']);
        return true;
    }
    else return false;
}

function getAccounts(){
    $doc = new DOMDocument;
    $doc->load($GLOBALS['acctpath']);
    $xpath = new DOMXPath($doc);
    $query = "/accounts/account";
    $count = $xpath->query($query)->length;
    echo '<br><div style="overflow: auto;max-height: 500px"><table style="border-collapse:collapse; border: 1px solid black;padding:5px"><tr style="background-color:white;color:black">
          <th style="border: 1px solid black;width: 20%;padding:5px">Account Type</th>
          <th style="border: 1px solid black;width: 20%;padding:5px">First Name</th>
          <th style="border: 1px solid black;width: 20%;padding:5px">Last Name</th>
          <th style="border: 1px solid black;width: 20%;padding:5px">Address</th>
          <th style="border: 1px solid black;width: 20%;padding:5px">E-mail</th>';
    for($i = 0; $i < $count; $i++){
        echo '<tr style="border: 1px solid black;padding:5px"><td>'.$xpath->evaluate($query)->item($i)->getAttribute('type').'</td>';
        echo '<td style="border: 1px solid black;padding:5px">'.$xpath->evaluate($query.'/firstname')->item($i)->nodeValue.'</td>';
        echo '<td style="border: 1px solid black;padding:5px">'.$xpath->evaluate($query.'/lastname')->item($i)->nodeValue.'</td>';
        echo '<td style="border: 1px solid black;padding:5px">'.$xpath->evaluate($query.'/address')->item($i)->nodeValue.'</td>';
        echo '<td style="border: 1px solid black;padding:5px">'.$xpath->evaluate($query.'/email')->item($i)->nodeValue.'</td></tr>';
    }
    echo '</table></div>';
}

function getProducts(){
    $prods = simplexml_load_file($GLOBALS['prodpath']);
	echo '<hr>';
    for ($i = 0; $i < count($prods->children()); $i++){
		echo '<a href="album.php?album='.$prods->album[$i]->id.'"><img src="'.$prods->album[$i]->albumart.'" width="200" height="200"/></a>'."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        if(($i+1)%4 == 0){
			echo "<br><hr>";
		}
		/*echo '<br>Album Title: <a href="album.php?album='.$prods->album[$i]->id.'">'.$prods->album[$i]->albumtitle.'</a><br>';
        echo 'Album Artist: '.$prods->album[$i]->artist.'<br>';
        echo 'Genre: '.$prods->album[$i]->genre.'<br>';
        echo 'Desc: '.$prods->album[$i]->desc.'<br>';
        echo 'Year: '.$prods->album[$i]->year.'<br>';
        *//*for ($j = 0; $j < count($prods->albums[$i]->songs->children()); $j++){
            echo "$name2 => $data<br>";*/
    }
	echo'<hr>';
}

function getProducts2(){
    $prods = simplexml_load_file($GLOBALS['prodpath']);
		echo '<ul>Artist:';
    for ($i = 0; $i < count($prods->children()); $i++){
		/*
		echo '<a href="album.php?album='.$prods->album[$i]->id.'"><img src="'.$prods->album[$i]->albumart.'" width="200" height="200"/></a>';
        if(($i+1)%4 == 0){
			echo "<br><hr>";
		}*/
		//echo '<br>Album Title: <a href="album.php?album='.$prods->album[$i]->id.'">'.$prods->album[$i]->albumtitle.'</a><br>';
        echo '<li><a href="album.php?album='.$prods->album[$i]->id.'">'.$prods->album[$i]->artist.'</a><br></li>';
        //echo 'Genre: '.$prods->album[$i]->genre.'<br>';
        //echo 'Desc: '.$prods->album[$i]->desc.'<br>';
        //echo 'Year: '.$prods->album[$i]->year.'<br>';
        /*for ($j = 0; $j < count($prods->albums[$i]->songs->children()); $j++){
            echo "$name2 => $data<br>";*/
    }
}

function getProducts3(){
    $prods = simplexml_load_file($GLOBALS['prodpath']);
		echo'<ul> Genre';
    for ($i = 0; $i < count($prods->children()); $i++){/*
		echo '<a href="album.php?album='.$prods->album[$i]->id.'"><img src="'.$prods->album[$i]->albumart.'" width="200" height="200"/></a>';
        if(($i+1)%4 == 0){
			echo "<br><hr>";
		}*/
		//echo '<br>Album Title: <a href="album.php?album='.$prods->album[$i]->id.'">'.$prods->album[$i]->albumtitle.'</a><br>';
        echo '<li><a href="album.php?album='.$prods->album[$i]->id.'">'.$prods->album[$i]->genre.'</a><br></li>';
        //echo 'Genre: '.$prods->album[$i]->genre.'<br>';
        //echo 'Desc: '.$prods->album[$i]->desc.'<br>';
        //echo 'Year: '.$prods->album[$i]->year.'<br>';
        /*for ($j = 0; $j < count($prods->albums[$i]->songs->children()); $j++){
            echo "$name2 => $data<br>";*/
    }
}

function getProduct($id){
	$id=$id-1;
    $prods = simplexml_load_file($GLOBALS['prodpath']);
	for ($i = 0; $i < count($prods->children()); $i++){
		if($i==$id){
		//	echo '<br><a href="album.php?album='.$prods->album[$i]->id.'"><img src="'.$prods->album[$i]->albumart.'" width="300" height="300"/></a><br/>';
			echo '<br>Album Title:' .$prods->album[$i]->albumtitle.'</a><br>';
			echo 'Album Artist: '.$prods->album[$i]->artist.'<br>';
			echo 'Genre: '.$prods->album[$i]->genre.'<br>';
			echo 'Desc: '.$prods->album[$i]->desc.'<br>';
			echo 'Year: '.$prods->album[$i]->year.'<br><br>';
        }
		/*for ($j = 0; $j < count($prods->albums[$i]->songs->children()); $j++){
            echo "$name2 => $data<br>";*/
    }
}

function getPic($id){
	$id=$id-1;
    $prods = simplexml_load_file($GLOBALS['prodpath']);
	for ($i = 0; $i < count($prods->children()); $i++){
		if($i==$id){
			echo '<img src="'.$prods->album[$i]->albumart.'" width="400" height="400"/><br/>';}
	 }
}

?>
